# -*- coding: UTF-8 -*-
# Author: Damon(wuud1)
# CreateDate: 
# Message:  使用webdriver访问长安官网, 并获取部分车型对应信息

# from untils.MysqlTools import MysqlTools
import pymongo
import re
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
# from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import time
import requests
from untils.yun_da_ma import code_verificate
from pprint import pprint
# from pyvirtualdisplay import Display
import os
from setting import *
import json

# 无界面模式
def ChromeDriverNOBrowser(driverPath):
    caps = DesiredCapabilities.CHROME
    caps['loggingPrefs'] = {'performance': 'ALL'}
    chrome_options = Options()
    # chrome_options.add_argument('--no-sandbox')  # 解决DevToolsActivePort文件不存在的报错
    # chrome_options.add_argument('--hide-scrollbars')  # 隐藏滚动条, 应对一些特殊页面
    # chrome_options.add_argument('blink-settings=imagesEnabled=false')  # 不加载图片, 提升速度
    # chrome_options.binary_location = r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"  # 手动指定使用的浏览器位置
    chrome_options.add_argument('--headless')  #浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败
    chrome_options.add_argument('--disable-gpu')  # 谷歌文档提到需要加上这个属性来规避bug
    chrome_options.add_argument('window-size=1920x1080') #指定浏览器分辨率
    driverChrome = webdriver.Chrome(executable_path=driverPath, chrome_options=chrome_options)
    return driverChrome

# 有界面
def ChromeDriverBrowser(driverPath):
    caps = DesiredCapabilities.CHROME
    caps['loggingPrefs'] = {'performance': 'ALL'}
    driverChrome = webdriver.Chrome(executable_path=driverPath)
    driverChrome.set_window_size(1440, 900)
    return driverChrome


class ToolsBox:

    def __init__(self, isdisplay=False):
        if isdisplay:
            self.browser = ChromeDriverBrowser(driverPath)
        else:
            self.browser = ChromeDriverNOBrowser(driverPath)
        self.wait = WebDriverWait(self.browser, 30)
        self.loginPage = 'http://epc.changan.com.cn:8080/front/login.html'
        self._dict = {}
        self._id = 485
        self.db = pymongo.MongoClient(host='192.168.10.222', port=27017)['changan']["carCode"]

    # def __del__(self):
    #     try:
    #         self.browser.close()
    #         self.browser.quit()
    #     except:
    #         pass
    #     os.system('pkill -f chromedriver')

    def verifyCode2local(self):
        imgVeri = self.wait.until(EC.presence_of_element_located((By.XPATH, '//img[@id="identifying"]')))
        imgSrc = imgVeri.get_attribute('src')
        print(imgSrc)
        imgCookies = {
            "JSESSIONID": self.browser.get_cookie("JSESSIONID").get("value")
        }
        imgHeaders = {
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36",
            "Referer": self.browser.current_url
        }
        # print(imgCookies)
        # print(imgHeaders)
        response = requests.get(url=imgSrc, headers=imgHeaders, cookies=imgCookies)
        with open(verifyCodeName, 'wb') as v:
            v.write(response.content)

    def get_verifyCode(self):
        self.verifyCode2local()  # 保存验证码图片到本地
        rs = code_verificate(verifyCodeName, ydm_username, ydm_password, ydm_appId, ydm_appKey,
                             code_type=1006)
        verifyCode = rs[0]
        # verifyCode = 'xxxx'
        print(verifyCode)
        return verifyCode

    def _input(self):
        iptUser = self.wait.until(EC.presence_of_element_located((By.XPATH, '//input[@id="username"]')))
        iptPasw = self.wait.until(EC.presence_of_element_located((By.XPATH, '//input[@id="password"]')))
        iptVeri = self.wait.until(EC.presence_of_element_located((By.XPATH, '//input[@id="identifyingCode"]')))

        # 输入
        iptUser.clear()
        iptUser.send_keys(ca_username)
        iptPasw.clear()
        iptPasw.send_keys(ca_password)
        verifyCode = self.get_verifyCode()
        iptVeri.clear()
        iptVeri.send_keys(verifyCode)
        buttonLogin = self.wait.until(EC.presence_of_element_located((By.XPATH, '//button[contains(@class, "login_btn")]')))
        self.browser.get_log('performance')
        buttonLogin.click()
        loginResult = self.isLogin()
        if loginResult == 0:  # 登录错误, 递归处理
            self.errorNum += 1
            print("登录错误, 重试第{}次".format(self.errorNum))
            if self.errorNum == 3:
                self.errorNum = 0
                return loginResult
            return self._input()
        return loginResult


    def isLogin(self):
        '''1: 登录成功
            0: 验证码错误
            -1: 账号密码错误'''
        time.sleep(1)
        try:
            _span = self.browser.find_element_by_xpath('//span[contains(text(), "重庆都成万禾汽车服务有限公司")]')  # 如果定位元素成功,则登录成功
            return 1
        except:
            return 0


    def _carCodeClick(self, _index):
        # print(_index)
        _select = self.wait.until(EC.presence_of_element_located((By.XPATH, '//div[@class="layui-select-title"][1]')))
        _select.click()
        time.sleep(0.5)
        elm_carCode = self.wait.until(EC.presence_of_all_elements_located(
            (By.XPATH, '//div[@class="layui-unselect layui-form-select layui-form-selected"][1]/dl[1]/dd')))[_index]
        print(elm_carCode.text)
        self._dict["carCode"] = elm_carCode.text.strip()
        elm_carCode.click()
        time.sleep(1)

    def get_finaData(self):
        time.sleep(1)
        self.wait.until(EC.presence_of_element_located((By.XPATH, '//label[contains(text(), "车型状态号")]/following-sibling::div[1]/div/div'))).click()
        time.sleep(0.5)
        finaDataList = self.wait.until(EC.presence_of_all_elements_located((By.XPATH, '//label[contains(text(), "车型状态号")]/following-sibling::div[1]//dd[position()>1]')))
        finaData = []
        for elm in finaDataList:
            _text = elm.text
            finaData.append(_text)
        for tail in finaData:
            self._dict["carTail"] = tail
            self._dict["_id"] = self._id
            self._id += 1
            self._dict["isold"] = 1
            try:
                print(self._dict)
                self.db.insert(self._dict)
            except Exception as e:
                print(e.__repr__())

    def carCodeClick(self):
        # carCodeList = self.wait.until(EC.presence_of_all_elements_located((By.XPATH, '//div[@class="layui-unselect layui-form-select"][1]/dl[1]/dd')))
        carCodeList = self.wait.until(EC.presence_of_all_elements_located((By.XPATH, '//label[contains(text(), "车型号")]/following-sibling::div[1]//dd')))
        _length = len(carCodeList)
        print(_length)
        for i in range(_length):
            try:
                self._carCodeClick(i)
                self.get_finaData()
            except:
                break
        print("点选车型号结束")

    def _carClick(self, _index):
        elm = self.wait.until(EC.presence_of_all_elements_located((By.XPATH, '//div[@class="imgbox"]')))[_index]
        elm_carName = elm.find_element_by_xpath('.//span')
        carName = elm_carName.text
        print(carName)
        self._dict["carModel"] = carName
        elm_carName.click()
        # _ = self.wait.until(EC.presence_of_element_located((By.XPATH, '//iframe[@id="mainIframe"]')))
        # self.browser.switch_to_frame("mainIframe")
        _ = self.wait.until(EC.presence_of_element_located((By.XPATH, '//div[@class="layui-select-title"]/input')))
        time.sleep(3)
        # 开始点选车型号
        self.carCodeClick()
        _back = self.wait.until(EC.presence_of_element_located((By.XPATH, '//a[contains(@title, "返回")]')))
        _back.click()
        time.sleep(3)

    def _getData(self):
        # time.sleep(5)
        # 切换到mainIframe
        self.browser.switch_to_default_content()
        # self.browser.switch_to.default_content()
        _ = self.wait.until(EC.presence_of_element_located((By.XPATH, '//iframe[@id="mainIframe"]')))
        self.browser.switch_to_frame("mainIframe")
        # 获取车系数量
        carList = self.wait.until(EC.presence_of_all_elements_located((By.XPATH, '//div[@class="imgbox"]')))
        carLength = len(carList)
        print(carLength)  # 元素个数
        for i in range(carLength):
            self._carClick(i)
        time.sleep(5)
        print("点击完毕")

    def _getDataOld(self):
        # 切换到mainIframe
        self.browser.switch_to_default_content()
        # self.browser.switch_to.default_content()
        _ = self.wait.until(EC.presence_of_element_located((By.XPATH, '//iframe[@id="mainIframe"]')))
        self.browser.switch_to_frame("mainIframe")
        # 点击老版EPC
        # TODO
        oldEpc = self.wait.until(EC.presence_of_element_located((By.XPATH, '//button[@id="add"]')))
        oldEpc.click()
        time.sleep(5)
        # 获取车系数量
        carList = self.wait.until(EC.presence_of_all_elements_located((By.XPATH, '//div[@class="imgbox"]')))
        carLength = len(carList)
        print(carLength)  # 元素个数
        for i in range(12, 32):
            self._carClick(i)
            time.sleep(3)
        time.sleep(5)
        print("点击完毕")

    def handleCookies(self, currenCookies):
        _dict = {}
        c_l = []
        for info in currenCookies:
            name = info.get("name", "")
            value = info.get("value", "")
            _dict[name] = value
            s = "{}={}".format(name, value)
            c_l.append(s)
        return "; ".join(c_l)

    def _getCookies(self):
        currenCookies = self.browser.get_cookies()
        finaCookies = self.handleCookies(currenCookies)
        return finaCookies

    def _getAuthorization(self):
        logs = str([json.loads(log['message'])['message'] for log in self.browser.get_log('performance')])
        Authorization = re.findall(r"'Authorization': '(.*?)'", logs)[0]
        return Authorization

    def getData(self):
        # 首先进入登录界面
        self.browser.get(url=self.loginPage)
        loginResult = self._input()  # 登录完成
        if loginResult == 1:
            cookies = self._getCookies()
            Authorization = self._getAuthorization()
        else:
            pass

        # 开始获取数据
        # self._getData()
        self._getDataOld()



    def run(self):
        try:
            self.getData()
        except Exception as e:
            print(e.__repr__())

if __name__ == '__main__':
    tools = ToolsBox(isdisplay=True)
    tools.run()






















